package com.probiz.estore.imports.handler.catalog.productCategory;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.probiz.estore.catalog.service.ProductCategoryManager;
import com.probiz.estore.catalog.util.CatalogCodeGenerator;
import com.probiz.estore.common.model.catalog.ProductCategory;
import com.probiz.estore.imports.handler.ColumnHandler;
import com.probiz.estore.imports.handler.basic.ColumnBasicHandler;
import com.probiz.estore.imports.model.Column;
import com.probiz.estore.imports.model.ImportModel;

public class CategoryCodeHandler extends ColumnBasicHandler implements ColumnHandler{
	private Logger logger = Logger.getLogger(CategoryCodeHandler.class);
	protected ProductCategoryManager	productCategoryManager	= null;
	public void setProductCategoryManager(ProductCategoryManager productCategoryManager) {
		this.productCategoryManager = productCategoryManager;
	}

	public void setProperty(ImportModel importModel, Column column)	throws Exception {
		ProductCategory category=(ProductCategory)importModel.getTarget();
		String value = column.getValue();
		if(StringUtils.isBlank(value)){
			//case: -----------没有设置目录编码-----------
			//start:设置目录编码并检查
			if(null ==category.getCategoryId()){
				boolean isCodeAvailable = false;
				do{
					String code = CatalogCodeGenerator.generateProductCategoryCode();
					Long size = productCategoryManager.getSizeByCategoryCodeByNotCategoryId(code, category.getCategoryId());
					if(size==0){
						//该编码可用
						isCodeAvailable = true;
						category.setCategoryCode(code);
					}
				}while(!isCodeAvailable);
			}
			//end:设置目录编码并检查
		}else{
			//case: -----------设置目录编码-----------
			//start:设置目录编码并检查
			//用getSizeByCategoryCodeByNotCategoryId而不用getByCode的原因在于调用后者的时候会有update操作，造成数据库有两个相同code的商品，出错
			Long size = productCategoryManager.getSizeByCategoryCodeByNotCategoryId(value, category.getCategoryId());
			
			if(size>=1){
				//设置结果
				importModel.setResult(ImportModel.RESULT_ERROR);
				String msg = "目录编码("+value+")已被其他目录使用，请选择其他编码。无法导入";
				logger.error(msg);
				importModel.setMsg(msg);
				return;
			}else{
				category.setCategoryCode(value);
			}
			//end:设置目录编码并检查
		}
		
		//设置结果
		importModel.setResult(ImportModel.RESULT_SUCCESS);
	}
	

}
